package com.mit.wx.interceptor;

import com.mit.wx.conf.AuthConfiguration;
import com.mit.wx.util.AccessAuthUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 2018/10/20 Create by 郭文梁
 * AccessAuthInterceptor
 * 访问权限控制
 *
 * @author 郭文梁
 * @date 2018/10/20
 */
@Slf4j
public class AccessAuthInterceptor implements HandlerInterceptor {
    private AuthConfiguration configuration;

    public AccessAuthInterceptor(AuthConfiguration configuration) {
        this.configuration = configuration;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        boolean granted = AccessAuthUtil.checkAuth(request);
        if (!granted) {
            try {
                response.sendRedirect(configuration.getLoginPath());
            } catch (IOException e) {
                log.error("Redirect fail,{}", e);
                e.printStackTrace();
            }
        }
        return granted;
    }

}
